package dq.study.nio.java.pipe;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.Charset;

/**
 * NIO 管道
 *
 * @author dongqun
 * @Description:
 * @date 2021/6/21 10:53
 */
public class Demo {
    public static void main(String[] args) throws IOException {
        Pipe pipe = Pipe.open();
        Pipe.SinkChannel sink = pipe.sink();

        ByteBuffer buffer = ByteBuffer.allocate(100);
        buffer.clear();
        buffer.put("ew String to write to file..".getBytes());
        buffer.flip();
        while (buffer.hasRemaining()) {
            sink.write(buffer);
        }


//        String newData = "New String to write to file..." + System.currentTimeMillis();
//        ByteBuffer buf = ByteBuffer.allocate(48);
//        buf.clear();
//        buf.put(newData.getBytes());
//        buf.flip();
////        while(buf.hasRemaining()) {
//            sink.write(buf);
////        }


        ByteBuffer target = ByteBuffer.allocate(200);
        Pipe.SourceChannel source = pipe.source();
        source.read(target);
//        target.flip();
//        byte[] bytes = target.array();
//        System.out.println(new String(bytes));

        CharBuffer charBuffer = Charset.forName("UTF-8").decode(target);
        charBuffer.flip();
        char[] chars = charBuffer.array();
        System.out.println(new String(chars));


    }

}
